package com.china.produce.aes;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/11/5
 */
public class AESEncryptionDemo {

    public static String encryptAES(String data, String key, String iv) throws Exception {
        // 初始化 Cipher
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());

        // 加密
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedData = cipher.doFinal(data.getBytes());

        // 将加密结果编码为 Base64 字符串
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public static void main(String[] args) {
        // 示例密钥和 IV（16 字节），需要与前端保持一致
        String key = "1234567890123456"; // 16 字节的密钥
        String iv = "1234567890123456";  // 16 字节的初始化向量

        // 待加密的数据
        String data = "{\"username\":\"testUser\", \"password\":\"testPassword\"}";

        try {
            // 加密数据
            String encryptedData = encryptAES(data, key, iv);
            System.out.println("加密后的数据 (Base64): " + encryptedData);

            // 将加密后的数据传输给前端（如通过 HTTP 响应发送）
        } catch (Exception e) {
            System.err.println("加密失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
